package net.lastcoder.ifserver.script;

import jdk.nashorn.api.scripting.ScriptObjectMirror;
import net.lastcoder.ifserver.game.Client;
import net.lastcoder.ifserver.game.GameManager;
import net.sf.cglib.core.ReflectUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author WenYF
 * @email wenyongfu@huohaoyun.cn
 * @since 2021/10/8
 */
public class ScriptManage {    
    private static final Logger Log = LoggerFactory.getLogger(ScriptManage.class);

    private static class SingletonHolder {
        private static final ScriptManage instance = new ScriptManage();
    }

    public static ScriptManage getInstance() {
        return SingletonHolder.instance;
    }
    
    private String dir;
    private ScriptEngine scriptEngine;
    public void setDir(String dir) {
        this.dir = dir;

        reload();
    }
    
    public void reload() {
        scriptEngine = new ScriptEngineManager().getEngineByExtension("js");
        try {
            Bindings bindings = scriptEngine.createBindings();
            bindings.put("game", GameManager.getInstance());
            scriptEngine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
            scriptEngine.eval(new FileReader(new File(dir, "Base.js")));
            scriptEngine.eval(new FileReader(new File(dir, "Main.js")));
        } catch (ScriptException | FileNotFoundException e) {
            Log.error(e.getLocalizedMessage(), e);
        }
    }

    /**
     * 开启监视
     */
    public void startWatcher() {
        
    }
    
    public void processMessage(Client client, String msg) {
        ScriptEngine scriptEngine = obtainScriptEngine();
        ScriptObjectMirror main = (ScriptObjectMirror) scriptEngine.get("main");

        main.call(null, 2, client, msg);
    }
    
    public void processFrame() {
        ScriptEngine scriptEngine = obtainScriptEngine();
        if (scriptEngine == null) {
            return;
        }
        ScriptObjectMirror main = (ScriptObjectMirror) scriptEngine.get("main");

        main.call(null, 1);
    }
    
    private ScriptEngine obtainScriptEngine() {
        // 初始化环境
        return scriptEngine;
    }
    
    
    
    
    
}
